package com.my.yc.d0316;

import com.google.gson.Gson;
import com.my.yc.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(value = "/QueryBookServlet.s")
public class QueryBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");

        String bookname = req.getParameter("bookname");
        String bookauthor = req.getParameter("bookauthor");

        Integer pageSize = Integer.valueOf(req.getParameter("pageSize"));
        Integer page = Integer.valueOf(req.getParameter("currentPage"));
        String sql = "select * from books where 1=1";
        List<Object> params = new ArrayList<>();

        if (bookname != null && bookname.isEmpty() == false){
            sql += " and bookname like ?";
            params.add("?" + bookname + "?");
        }
        if (bookauthor != null && bookauthor.trim().isEmpty() == false){
            sql += " and bookauthor like ?";
            params.add("?" + bookauthor + "?");
        }
        int begin = pageSize * (page - 1); // 起始行
        long total = DBHelper.count(sql, params.toArray());

        //查询数据  从起始行开始找pageSize行数据
        List<Map<String, Object>> data = DBHelper.selectListMap(sql + " limit ?, ?", begin, pageSize);

        Map<String,Object> res = new HashMap<>();
        res.put("total",total);
        res.put("data", data);
        String json = new Gson().toJson(res);
        resp.getWriter().print(json);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
